package org.xurui.sxl.protocol.command.impl;

import org.jetlinks.core.message.DeviceMessage;
import org.jetlinks.core.message.codec.FromDeviceMessageContext;
import org.jetlinks.core.message.property.ReportPropertyMessage;
import org.xurui.sxl.protocol.command.CmdCodec;
import org.xurui.sxl.protocol.enums.CommandEnum;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 定位辅助请求
 */
public class CmdCodec_GETGPS implements CmdCodec {
    @Override
    public boolean supportsCmd(String cmd) {
        return CommandEnum.GETGPS.name().equals(cmd);
    }

    @Override
    public boolean supportsRelayCmd() {
        return false;
    }

    @Override
    public List<DeviceMessage> parsePayload(String payload, FromDeviceMessageContext context) {
        //定位辅助请求 设备上报 TODO 没有 SV,BAT
        //格式：*XX,YYYYYYYYYYYYYYY,GETGPS,HHMMSS,MCC,MNC,TAC,CELLID,DDMMYY,tracker_status#
        //例子：*TJ,866104040001458,GETGPS,174904,460,00,9360,5523,110611,FFFFFFFF#
        //回复格式：*XX,YYYYYYYYYYYYYYY,GETGPS,HHMMSS,latitude,longitude#
        //回复示例：*TJ,866104040001458,GETGPS,174904,22.569882,113.863636#
        //参数说明：GPS 信息 latitude,longitude WGS84 度格式 dd.dddddd,ddd.dddddd
        //参数说明：基站信息 MCC,MNC,LAC,CELLID 详见第一部分 VI 基站消息
        ReportPropertyMessage report = ReportPropertyMessage.create();
        String[] payloadArr = payload.replaceAll("\\*", "").split(",");
        String deviceId = payloadArr[1];
        report.setCode(CommandEnum.GETGPS.name());
        report.setDeviceId(deviceId);
        report.setMessageId(deviceId + "_" + payloadArr[3]);
        report.setTimestamp(System.currentTimeMillis());
        Map<String, Object> properties = new HashMap<>();
        properties.put("uptime",payloadArr[3]);
        properties.put("mcc",payloadArr[4]);
        properties.put("mnc",payloadArr[5]);
        properties.put("tac",payloadArr[6]);
        properties.put("cellid",payloadArr[7]);
        properties.put("upday",payloadArr[8]);
        String trackerStatusHex = payloadArr[9];

        Map<String,Object> trackerStatusMap = parseTrackerStatus(trackerStatusHex);
        properties.put("trackerstatus",trackerStatusMap);
        report.setProperties(properties);
        //回复设备数据
        //TODO 暂时没找到设备回复消息的方法
        //TODO 没有回复参数 latitude,longitude
        /*String day= BinaryUtils.getDateFormat();
        String reply="*"+payloadArr[0]+","+deviceId+",V4,"+CommandEnum.GETGPS.name()+","+day;
        context.getSession()
            .send(EncodedMessage
                .simple(Unpooled.wrappedBuffer(reply.getBytes())))
            .subscribe();*/
        return genDeviceMessage(report);
    }
}
